import React from 'react';
import { Attachments, Sender } from '@ant-design/x';
import { Badge, Button, message, Upload } from 'antd';
import { CloudUploadOutlined, PaperClipOutlined } from '@ant-design/icons';
import { GetProp } from 'antd/es';
import { uploadFileChat } from '@/services/backend/chatController';

interface FileUploaderProps {
  headerOpen: boolean;
  setHeaderOpen: (open: boolean) => void;
  attachedFiles: GetProp<typeof Attachments, 'items'>;
  setAttachedFiles: React.Dispatch<React.SetStateAction<GetProp<typeof Attachments, 'items'>>>;
  uploading: boolean;
  setUploading: React.Dispatch<React.SetStateAction<boolean>>;
}

const FileUploader: React.FC<FileUploaderProps> = ({
  headerOpen,
  setHeaderOpen,
  attachedFiles,
  setAttachedFiles,
  uploading,
  setUploading,
}) => {
  const handleFileChange: GetProp<typeof Attachments, 'onChange'> = (info) => {
    setAttachedFiles(info.fileList);
    console.log(info);
  };

  const attachmentsNode = (
    <Badge dot={attachedFiles.length > 0 && !headerOpen}>
      <Button type="text" icon={<PaperClipOutlined />} onClick={() => setHeaderOpen(!headerOpen)} />
    </Badge>
  );

  const senderHeader = (
    <Sender.Header
      title="上传文件"
      open={headerOpen}
      onOpenChange={setHeaderOpen}
      styles={{
        content: {
          padding: 0,
        },
      }}
    >
      <Attachments
        maxCount={1}
        accept=".txt"
        beforeUpload={(file) => {
          const isLt2M = file.size / 1024 / 1024 < 20;
          if (!isLt2M) {
            message.error('上传失败, 上传文件大小不能超过 5MB');
            return Upload.LIST_IGNORE;
          }
          return isLt2M;
        }}
        customRequest={async (options) => {
          const { onSuccess, onError, file } = options;
          setUploading(true);
          try {
            await uploadFileChat({ separator: '####' }, { file: file as File }).then((res) => {
              if (res.code === 0) {
                message.success('上传成功');
                onSuccess?.(res);
              } else {
                message.error('上传失败');
                onError?.(new Error(res.message));
              }
            });
          } catch (error) {
            message.error('上传失败');
          } finally {
            setUploading(false);
          }
        }}
        items={attachedFiles}
        onChange={handleFileChange}
        placeholder={(type) =>
          type === 'drop'
            ? { title: 'Drop file here' }
            : {
                icon: <CloudUploadOutlined />,
                title: 'Upload files',
                description: 'Click or drag files to this area to upload',
              }
        }
      />
    </Sender.Header>
  );

  return {
    attachmentsNode,
    senderHeader,
  };
};

export default FileUploader;
